const { productService,appoint,sequelize,memberInfo } = require('../../dbConfig/index')
const {Op, where} = require('sequelize')

// 获取产品
const getProd = async (ctx,next) => {
	const body = ctx.request.body
	let res = null;
    res = await productService.findAll({
        where: {
            merchant_id: body.merchant_id
        },
        include: [{
            model: appoint,
            required: false,  // 允许没有预约的产品
            where: {
					appoint_state: {
						[Op.or]: ['1', '2']  // 查询状态为 1 或 2
					}  // 只查询有效的预约状态
            },
            attributes: ['appointment_time']  // 只选择预约时间
        }]
    });
    ctx.body = { code: 200, data: res, msg: '成功' };
}
// 创建预约
const createAppoint = async (ctx,next)=>{
	const {service_id,appointment_time,merchant_id} = ctx.request.body
	if(!(merchant_id&&service_id&&appointment_time)){
		ctx.body={code:1,data:null,msg:'参数缺失'}
		return
	}
	const memberDetali = await memberInfo.findOne({where:{
		user_id:ctx.state.user_id
	}})
	if (!memberDetali) {
		ctx.status = 400; // Bad Request
		ctx.body = { code: 1, msg: '用户不存在，无法创建预约' };
		return;
	}
	const serveInfo = await productService.findOne({where:{
		Id:service_id,
		merchant_id:merchant_id
	}})
	if (!serveInfo) {
		ctx.status = 400; // Bad Request
		ctx.body = { code: 1, msg: '服务不存在，无法创建预约' };
		return;
	}
	let transaction = await sequelize.transaction(); //使用事务
	if(serveInfo.is_shop_vip==='2' && memberDetali.member_type.includes('2') && memberDetali.lines_count>0){
		// 该服务商品支持次卡消费 用户也满足条件
			await memberInfo.update({
				lines_count:String(memberDetali.lines_count - 1)
			},{where:{user_id:ctx.state.user_id},transaction})
			await appoint.create({
				user_id:ctx.state.user_id,
				service_id:service_id,
				merchant_id:merchant_id,
				appointment_time:appointment_time,
				appoint_state:'1',
				paly_state:'2'
			},{transaction})
			await transaction.commit();
			ctx.body = {code:200,data:null,msg:'预约成功'}
	}else if(serveInfo.is_shop_vip==='3'&&memberDetali.member_type.includes('3') && Number(memberDetali.lines_num)>=Number(serveInfo.service_price)){ // 该商品支持超划算 用户也满足条件
			await memberInfo.update({
				lines_num:String(Number(memberDetali.lines_num) - Number(serveInfo.service_price))
			},{
				where:{user_id:ctx.state.user_id},transaction})
				await appoint.create({
					user_id:ctx.state.user_id,
					service_id:service_id,
					merchant_id:merchant_id,
					appointment_time:appointment_time,
					appoint_state:'1',
					paly_state:'3'
				},{transaction})
				await transaction.commit();
				ctx.body = {code:200,data:null,msg:'预约成功'}
	}else{
		//告诉前端 只能用微信支付
		ctx.body={code:1,data:{member_type:1},msg:"余额不足"}
	}
	
	// TODO 微信支付, 支付后创建预约数据
}
// 获取当前有效的用户预约 会员纬度
const getUserAppoint = async (ctx,next)=>{
	const user_id = ctx.state.user_id// 当前登录用户ID
	try {
        // 查询用户的有效预约信息
        const userAppointments = await appoint.findAll({
            where: {
                user_id: user_id, // 根据用户ID查询
				merchant_id:ctx.request.body.merchant_id,
                appoint_state: { // 只查询有效的预约状态
                    [Op.or]: ['1', '2'] // 假设 1 和 2 是有效状态
                }
            },
            include: [{
                model: productService, // 联接产品服务信息
				as: 'productService', // 使用定义的别名
                required: true, // 确保只有有对应产品服务的预约被返回
                attributes: ['Id', 'service_name', 'service_price'] // 选择需要的字段
            }],
			order: [['appointment_time', 'ASC']]
        });

        // 返回结果
        ctx.body = {
            code: 200,
            data: userAppointments,
            msg: '成功'
        };
    } catch (error) {
        console.error('获取用户预约信息失败:', error);
        ctx.body = {
            code: 500,
            msg: '获取用户预约信息失败'
        };
    }
}

// 签到
const changeState = async (ctx,next)=>{
	const body = ctx.request.body
	await appoint.update({
		appoint_state:'2'
	},{
		where:{
			Id:body.Id
		}
	})
	ctx.body = {code:200,data:null,msg:'成功'}
}
module.exports = {
	getProd,
	createAppoint,
	getUserAppoint,
	changeState
}